import { Button, DatePicker, Select, Space, Tooltip } from "antd";
import { STATUS_ENUMS, STATUS_OPTIONS } from "./data";
import { DeleteOutlined, EditOutlined, ShareAltOutlined } from "@ant-design/icons";
import { useTableDialog } from "@/hooks/useTable";
import { del, page, pageTenantFunction, removeTenantFunction, saveTenantFunction, upt } from "./api";
import { page as pageFunction } from "@/views/sys/function/api";
import { useEffect, useState } from "react";
import CloudTable from "@/component/CloudTable";
import FormModal from "@/component/FormModal";
import { useFormDialog } from "@/hooks/useForm";
import dayjs from "dayjs";
import TableModal from "@/component/TableModal";

const Tenant = () => {

    /**
     * 表单提交
     */
    const onTenantFormCallback = (model) => {
        let data = {
            ...model,
            startDate: model.startDate?.format('YYYY-MM-DD'),
            endDate: model.endDate?.format('YYYY-MM-DD'),
        };
        tenantFormModal.onSubmit(data, tenantTable.onReload);
    }

    // 表单列
    const tenantItems = [
        {
            label: '名称',
            name: 'name',
            rules: [{ required: true, message: '请输入名称' }],
        },
        {
            label: '负责人',
            name: 'userId',
            rules: [{ required: true, message: '请输入负责人' }],
        },
        {
            label: '域名',
            name: 'domain',
        },
        {
            label: '规模',
            name: 'scale',
        },
        {
            label: '地址',
            name: 'address',
        },
        {
            label: '注册时间',
            name: 'startDate',
            render: <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
            rules: [{ required: true, message: '注册时间' }],
        },
        {
            label: '到期时间',
            name: 'endDate',
            render: <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
            rules: [{ required: true, message: '到期时间' }],
        },
        {
            label: '状态',
            name: 'status',
            rules: [{ required: true, message: '请选择状态' }],
            render: <Select placeholder='请选择状态' options={STATUS_OPTIONS()} />,
        },
    ];

    // 表单操作
    const tenantFormModal = useFormDialog({
        width: 600,
        // save: save,
        edit: upt,
        items: tenantItems,
        callback: onTenantFormCallback,
    });

    // 表格列
    const tenantColumns = [
        {
            title: '#',
            key: 'index',
            width: 50,
            fixed: 'left',
            align: 'center',
            render: (val, record, index) => {
                return index + 1;
            }
        },
        {
            title: '名称',
            key: 'name',
            dataIndex: 'name',
            ellipsis: true,
            search: 'default'
        },
        {
            title: '负责人',
            key: 'userId',
            dataIndex: 'userId',
            ellipsis: true,
            search: 'default'
        },
        {
            title: '域名',
            dataIndex: 'domain',
            key: 'domain',
            ellipsis: true,
            search: 'default'
        },
        {
            title: '规模',
            dataIndex: 'scale',
            key: 'scale',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '地址',
            dataIndex: 'address',
            key: 'address',
            width: 'auto',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '注册时间',
            dataIndex: 'startDate',
            key: 'startDate',
            ellipsis: true,
            search: 'date',
        },
        {
            title: '到期时间',
            dataIndex: 'endDate',
            key: 'endDate',
            ellipsis: true,
            search: 'date',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            ellipsis: true,
            search: 'selected',
            options: STATUS_OPTIONS(),
            render: val => STATUS_ENUMS[val] || '',
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 120,
            align: 'center',
            fixed: 'right',
            render: (val, row) => {
                let record = {
                    ...row,
                    startDate: dayjs(row.startDate, 'YYYY-MM-DD'),
                    endDate: dayjs(row.endDate, 'YYYY-MM-DD'),
                }
                let params = {
                    id: val,
                    data: {}
                }
                return (
                    <div>
                        <Tooltip title="编辑">
                            <Button type="text" size="small" icon={<EditOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => tenantFormModal.isOpenDialog(record, '编辑')} />
                        </Tooltip>
                        <Tooltip title="分配功能包">
                            <Button type="text" size="small" icon={<ShareAltOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => functionTableModal.isOpenDialog(params)} />
                        </Tooltip>
                        <Tooltip title="删除">
                            <Button type="text" size="small" icon={<DeleteOutlined />} style={{ margin: '0 4px', color: 'red' }} onClick={() => tenantTable.onRemove(val)} />
                        </Tooltip>
                    </div>
                )
            }
        }
    ];

    // 表格操作
    const tenantTable = useTableDialog({
        width: 1200,
        reload: page,
        remove: del,
        // batchRemove: batchDel,
        // tools: tenantTools,
        columns: tenantColumns,
    });

    const onSaveFunctionHandler = (model) => {
        let entity = {
            tenantId: functionTableModal.row?.id,
            data: {
                ...model,
                tenantId: functionTableModal.row?.id,
                startDate: model.startDate?.format('YYYY-MM-DD'),
                endDate: model.endDate?.format('YYYY-MM-DD'),
            }
        }

        functionFormModal.onSubmit(entity, functionTableModal.onReload);
    }

    // 员工下拉搜索
    const [functionOptions, setFunctionOptions] = useState([]);
    const onSearchFunctionHandle = (val) => {
        let query = { params: [{ field: 'name', expr: 'LIKE_LEFT', value: val }] };
        pageFunction(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name,
                value: item.id,
            }));
            setFunctionOptions(options);
        });
    }

    // 表单操作
    const functionFormModal = useFormDialog({
        // width: 600,
        // save: save,
        save: saveTenantFunction,
        callback: onSaveFunctionHandler,
        items: [
            {
                label: '功能包',
                name: 'functionId',
                render: <Select
                    showSearch
                    allowClear
                    placeholder="请输入功能包"
                    optionFilterProp="label"
                    filterOption={false}
                    onSearch={(val) => onSearchFunctionHandle(val)}
                    options={functionOptions}
                />
            },
            {
                label: '生效时间',
                name: 'startDate',
                render: <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
                rules: [{ required: true, message: '生效时间' }],
            },
            {
                label: '结束时间',
                name: 'endDate',
                render: <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
                rules: [{ required: true, message: '结束时间' }],
            },
        ],
    });

    // 表格工具栏
    const functionTools = () => {
        return (
            <Space>
                <Button type="primary" onClick={() => functionFormModal.isOpenDialog(undefined, '新增')} >新增</Button>
                <Button type='dashed' style={{ color: 'red' }} onClick={() => onRemoveTenantFunctionHandler()}>删除</Button>
            </Space>
        );
    }

    const onRemoveTenantFunctionHandler = () => {
        let query = {
            id: functionTableModal.row?.id,
            data: functionTableModal.selected
        }
        functionTableModal.onRemove(query);
    }

    // 功能包
    const functionTableModal = useTableDialog({
        title: '功能包',
        width: 600,
        reload: pageTenantFunction,
        remove: removeTenantFunction,
        // callback: onSaveFunctionHandler,
        tools: functionTools,
        columns: [
            {
                title: '#',
                key: 'index',
                width: 50,
                fixed: 'left',
                align: 'center',
                render: (val, record, index) => {
                    return index + 1;
                }
            },
            {
                title: '名称',
                dataIndex: 'functionName',
                key: 'functionName',
                width: 'auto',
            },
            {
                title: '生效时间',
                dataIndex: 'startDate',
                key: 'startDate',
                width: 'auto',
            },
            {
                title: '结束时间',
                dataIndex: 'endDate',
                key: 'endDate',
                width: 'auto',
            },
        ],
    });

    useEffect(() => {
        tenantTable.onReload();
    }, []);

    return (
        <>
            <CloudTable props={tenantTable} />
            <FormModal props={tenantFormModal} />
            <TableModal props={functionTableModal} />
            <FormModal props={functionFormModal} />
        </>
    );
};

export default Tenant;